/**
 * Created by jn-dinggao on 2017/7/12.
 */

//定义AppCtrl，注入自定义的restAPI服务
app.controller("AppCtrl", ["$scope", '$translate', '$localStorage', '$window', '$state',"restAPI", "serviceUtil","METHODS",'URL',
    function ($scope,$translate,$localStorage,$window,$state,restAPI,serviceUtil,METHODS,$cookieStore,URL) {

    // 测试 $http $resource
    //方式一：通过$http 访问REST接口
    /*var promise = restAPI.query(); // 同步调用，获得承诺接口
    promise.then(function(data) {  // 调用承诺API获取数据 .resolve
        $scope.user = data;
        console.log("query success!");
        console.log(data);
    }, function(data) {  // 处理错误 .reject
        console.log("query error!");
        console.log(data);
        $scope.user = {error: '用户不存在！'};
    });*/

    //方式二：通过$resource 访问REST接口
   /* var baseUrl = "http://localhost:8080/taxi/";
    var user = $scope.user = {
        userId : 1,
        password : '123456'
    }

    console.log('======METHODS========');
    console.log(METHODS);

    var promise = serviceUtil.excute(baseUrl+'infoUser/register',user,METHODS.register);

    promise.then(function(data) {  // 调用承诺API获取数据 .resolve
        console.log("query success!");
        console.log(data);
    }, function(data) {  // 处理错误 .reject
        console.log("query error!");
        console.log(data);
    });*/

        var vm = $scope.vm = {
            newPw : '',
            secondNewPw:''
        };

        // add 'ie' classes to html
        var isIE = !!navigator.userAgent.match(/MSIE/i);
        isIE && angular.element($window.document.body).addClass('ie');
        isSmartDevice( $window ) && angular.element($window.document.body).addClass('smart');

        // config
        $scope.app = {
            host: "http://112.74.73.143",
            name: '乐城后台管理系统',
            version: '1.0.0',
            // for chart colors
            color: {
                primary: '#7266ba',
                info:    '#23b7e5',
                success: '#27c24c',
                warning: '#fad733',
                danger:  '#f05050',
                light:   '#e8eff0',
                dark:    '#3a3f51',
                black:   '#1c2b36'
            },
            settings: {
                themeID: 1,
                navbarHeaderColor: 'bg-black',
                navbarCollapseColor: 'bg-white-only',
                asideColor: 'bg-black',
                headerFixed: true,
                asideFixed: false,
                asideFolded: false,
                asideDock: false,
                container: false
            }
        }

        // save settings to local storage
        if ( angular.isDefined($localStorage.settings) ) {
            $scope.app.settings = $localStorage.settings;
        } else {
            $localStorage.settings = $scope.app.settings;
        }
        $scope.$watch('app.settings', function(){
            if( $scope.app.settings.asideDock  &&  $scope.app.settings.asideFixed ){
                // aside dock and fixed must set the header fixed.
                $scope.app.settings.headerFixed = true;
            }
            // save to local storage
            $localStorage.settings = $scope.app.settings;
        }, true);

        // angular translate
        $scope.lang = { isopen: false };
        $scope.langs = {en:'English', de_DE:'German', it_IT:'Italian',cn:'chinese'};
        $scope.selectLang = $scope.langs[$translate.proposedLanguage()] || "English";
        $scope.setLang = function(langKey, $event) {
            // set the current lang
            $scope.selectLang = $scope.langs[langKey];
            // You can change the language during runtime
            $translate.use(langKey);
            $scope.lang.isopen = !$scope.lang.isopen;
        };

        $scope.logout = function(){
            $localStorage.user=null;
            $localStorage.permissionList=null;
            // $state.go("access.login");
            var promise = serviceUtil.excute('./infoUser/logout',null,METHODS.get);
            promise.then(function(data) {  // 调用承诺API获取数据 .resolve
                if(data.code == 1){
                    $state.go("access.login");
                }
            }, function(data) {  // 处理错误 .reject
                Lobibox.alert("error",{
                    msg:'登出失败，请重试！'
                });
            });
        };

        /**
         * 密码修改弹出模态框
         */
        $scope.pwmodify = function () {
            vm.newPw = "";
            vm.secondNewPw = "";
            $('#ModifyPwModal').modal('show');
        };

        /**
         * 密码修改
         */
        $scope.modifyPw = function () {
            if(vm.newPw == '' || vm.secondNewPw == ''){
                Lobibox.alert('error',{
                    msg:'密码不能为空'
                });
            }
            if(vm.newPw != vm.secondNewPw){
                Lobibox.alert('error',{
                    msg:'密码输入不一致！请重新输入'
                });
                return;
            }
            var param = {};
            param.newPw = vm.newPw;
            var promise = serviceUtil.excute('./infoUser/updatePw',param,METHODS.update);

            promise.then(function(data) {  // 调用承诺API获取数据 .resolve
                if(data.code == 1){
                    Lobibox.alert("success",{
                        msg:'密码修改成功，重新登陆！',
                        callback:function () {
                            $state.go("access.login");
                        }
                    });
                    $('#ModifyPwModal').modal('hide');
                }
            }, function(data) {  // 处理错误 .reject
                Lobibox.alert("success",{
                    msg:'密码修改失败，请重试！'
                });
            });
        };

        function isSmartDevice( $window )
        {
            // Adapted from http://www.detectmobilebrowsers.com
            var ua = $window['navigator']['userAgent'] || $window['navigator']['vendor'] || $window['opera'];
            // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
            return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
        }

        //监听子模块登陆信息
        $scope.$on("login.user",function (event,data) {
            $scope.user = $.extend({},true,data);
        });
        //页面刷新后，保存用户信息
        $scope.user = $localStorage.user ? $localStorage.user : {};
    }
]);